import api from "../../common/api.js";
import util from "../../utils/util.js";
import {
  getActiveStr,
} from "../../utils/utilsNew.js";
import locationBehavior from "../../behaviors/location.js";
import {
  xstShare
} from "../../common/subscribe.js";
import constant from "../../common/constant.js";
const computedBehavior = require("miniprogram-computed");
const modules = require("../../models/modules");
import * as homeFilterConfig from '../../models/homeFilterConfig'

var app = getApp();
var timer = null;
let locationswitchoff = false;
/** gio埋点 */
const _map = {
  NEWHOUSE: constant.XIN_FANG,
  RENT: constant.CHU_ZU,
  SALES: constant.ER_SHOU,
};
let pageNumber = 0; //当前页数
let maxPageNumber = 0; //当前数据的最大页数
let isLoadOver = false;
let pageSize = 20; //单页的数据条数
var listData = {},
  area = [], //区域 一级选择（区）
  distance = null, //距离
  price = [], //price价格
  room = [], //室数
  order = "",
  buildSize = [], //面积
  floor = [], //楼层
  direction = [], //朝向
  decorate = [], //装修
  buildType = [], //类型
  tag = []; //标签

const TAB_LIST_NAMES = ["SALES", "RENT", "NEWHOUSE"];

Component({
  behaviors: [computedBehavior, locationBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    hidden: Boolean,
    tabConentIndex: {
      type: Number,
      value: 0,
    },
    isNew: {
      type: Number,
      value: 0,
    },
    height: {
      type: String,
      value: 0,
    },
    haveHouse: {
      type: String,
      value: 0,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    headerHeight: 0, // 高度
    unread: 0,
    unreadCount: 0, //业主房源情报未读
    finger: false, //手指是否按住屏幕
    scrollTop: 0, //滚轴的位置
    scrollIng: false, //是否在滚动
    showGetCash: true, //领红包隐藏
    hideGetCash: true, //领红包显示
    loadMyApp: false, //是否添加到我的小程序
    informComent: "", //首页的消息通知内容
    informTime: "", //首页的消息通知滚动时间
    informDate: "", //首页的消息通知时间
    inform: false, //首页的消息通知
    getLocationCount: 0,
    pageLifetimesShowCount: 0,
    isFetchingHouse: true, //正在请求房源数据
    isCompleteNoHouse: null,
    currentBannerIndex: 0, //当前的banner
    onShowRefresh: false, //再次进入时刷新房源
    update: false, //是否需要更新
    bannerComponentIndex: 0,
    bannerComponentHeightList: ["0rpx", "230rpx"],
    aniStyle: false, //动画效果，默认slideup
    shareid: "", //分享的房源id
    detailContent: "", //房源详情
    shareShowDialog: false,
    // shareShowDialog: true,
    friendsShowDialog: false,
    pyqVisible: false,
    isDisabled: false,
    houseTypes: "SALES", //类型名称
    houseList: [],
    isChangeList: 0,
    isHouse: 0,
    backRefresh: false,
    inputData: "搜索小区名称或关键字",
    resblock_name: "", //小区搜索词
    isFirst: false, //是否是第一次进入该页面，用来判断列表无房源时显示去添加房源还是显示暂无房源图片
    fixedState: false, //是否定位
    listTabShowDialog: false,
    showDialog: false,
    areaTitleText: "区域", //区域筛选显示文字
    priceTitleText: "价格", //价格筛选显示文字
    roomTitleText: "房型", //房型筛选显示文字
    moreTitleText: "更多", //更多筛选显示文字
    tabHouseTypeState: 0, //房源列表状态 0 出售全部房源 1 出售我的房源 2 出租全部房源 3 出租我的房源
    currentId: 1,
    current: -1, //头部标题列表当前选中
    areas: [], //区域
    tabAreaTitleIndex: 0, //区域标题当前选中index
    areaIndex: 0, //区域中 区 选择当前选中index
    isAreaSecondShow: false, //区域中二级分类是否显示
    bizBlockIndex: 0, //区域中商圈当前选中index
    distanceIndex: 0, //区域 附近当前选中index
    priceArr: homeFilterConfig.priceArr, //出售价格
    priceRentArr: homeFilterConfig.priceRentArr, //出租价格
    minPriceValue: "", //输入最低价
    maxPriceValue: "", //输入最高价
    roomArr: homeFilterConfig.roomArr,
    moreSortActive: -1, //排序选中
    buildSize: homeFilterConfig.buildSize, //面积 最近更新：del.update_time, 最近跟进：fol.update_time  最近带看: show.update_time 总价:del.total_prices 单价:del.unit_price 面积:hou.build_size
    minBuildSizeValue: "", //输入最面积
    maxBuildSizeValue: "", //输入最面积
    floorArr: homeFilterConfig.floorArr,
    buildNumNewList: homeFilterConfig.buildNumNewList,
    directionArr: homeFilterConfig.directionArr,
    decorateArr: homeFilterConfig.decorateArr,
    buildTypeArr: homeFilterConfig.buildTypeArr,
    tagArr: homeFilterConfig.tagArr,
    filterSalesTypeArr: homeFilterConfig.filterSalesTypeArr,
    filterRentTypeArr: homeFilterConfig.filterRentTypeArr,
    filterTypeActive: 1,
    filterTypeIconActive: "iconkuaijiexinzeng",
    contentHeaderTitle: [], //原版本的title
    _contentHeaderTitle: [], //首页改版后用的title
    navList: {
      SALES: {
        titles: ["状态", "价格", "房型", "排序", "面积", "楼层", "朝向", "类型"],
      },
      RENT: {
        titles: ["状态", "价格", "房型", "排序", "面积", "楼层", "朝向", "类型"],
      },
      NEWHOUSE: {
        titles: ["排序", "单价", "在售状态", "楼盘状态"],
        sort: [{
            name: "单价从高到低",
            value: "desc",
            select: false
          },
          {
            name: "单价从低到高",
            value: "asc",
            select: false
          },
        ],
        sellState: [{
            name: "在售",
            value: "onSale",
            select: false
          },
          {
            name: "待售",
            value: "forSale",
            select: false
          },
        ],
        buildingState: [{
            name: "上架",
            value: "AVAILABLE",
            select: false
          },
          {
            name: "下架",
            value: "UNAVAILABLE",
            select: false
          },
        ],
        unitPrice: [{
            name: "1万以下",
            value: {
              max: 10000
            },
            select: false
          },
          {
            name: "1万～2万",
            value: {
              min: 10000,
              max: 20000
            },
            select: false
          },
          {
            name: "2万～3万",
            value: {
              min: 20000,
              max: 30000
            },
            select: false
          },
          {
            name: "3万～4万",
            value: {
              min: 30000,
              max: 40000
            },
            select: false
          },
          {
            name: "4万～5万",
            value: {
              min: 40000,
              max: 50000
            },
            select: false
          },
          {
            name: "5万～6万",
            value: {
              min: 50000,
              max: 60000
            },
            select: false
          },
          {
            name: "6万～7万",
            value: {
              min: 60000,
              max: 70000
            },
            select: false
          },
          {
            name: "7万～8万",
            value: {
              min: 70000,
              max: 80000
            },
            select: false
          },
          {
            name: "8万以上",
            value: {
              min: 80000
            },
            select: false
          },
        ],
      },
    },
    // 新房的数据选择数据
    newHouseSelectData: {},
    currentSelectNavIndex: 0,
    mainContentScrollId: "",
    inMarketNames: {
      SALES: "在售",
      RENT: "在租",
      NEWHOUSE: "新房",
    },
    selectMarketIndex: 0, //在售/下架 选择索引
    marketValues: ["AVAILABLE", "UNAVAILABLE"],
    modelBanners: [],
    cityName: ''
  },

  observers: {
    tabConentIndex() {
      // console.log("home 监听到 tabConentIndex", this.data.tabConentIndex);
      if (this.data.tabConentIndex == 0) {
        app.globalData.loginPromise.then(() => {
          this.getUnreadMesgCount();
          this.getPropertyOwner() //业主房源情报  未读
          modules.updateMemberCenter()
            .then((res) => {
              this.setData({
                isShowMemberCenter: res === '1' ? true : false,
              })
            })
        });

        if (this.data.showDialog) {
          this.setData({
            showDialog: false,
          });
        }
      }
    },

    contentHeaderTitle() {
      this.setData({
        _contentHeaderTitle: [this.data.contentHeaderTitle[0], "筛选"],
      });
    },

    isNew() {
      if (app.globalData.loginPromise) {
        app.globalData.loginPromise.then(() => {
          this.showAddApp();
        });
      }
    },
  },

  attached() {
    const that = this;
    app.globalData.systemPromise.then(({ navHeight }) => {
      this.setData({ headerHeight: navHeight});
    })
    app.globalData.loginPromise.then((content) => {
      this.getUnreadMesgCount()
      this.getPropertyOwner() //业主房源情报  未读
      modules.updateMemberCenter()
        .then((res) => {
          this.setData({
            isShowMemberCenter: res === '1' ? true : false,
          })
        })
      wx.nextTick(() => {
        this.getNotice();
      });
      this.myOnShow();
      try {
        if (app.globalData.sessionUser.extProps.wxMobile && app.globalData.sessionUser.extProps.wxMobile != null) {
          that.getLocation();
          that.setData({
            isFirst: false,
            url: util.ImagesUrl,
          });
        } else {
          that.setData({
            isFirst: true,
          });
        }
      } catch (error) {
        console.log('###err###', error);
      }
    });
  },

  pageLifetimes: {
    show: function (options) {
      console.log('页面切换')
      if (this.data.onShowRefresh) {
        app.globalData.loginPromise.then(() => {
          modules.updateMemberCenter()
            .then((res) => {
              this.setData({
                isShowMemberCenter: res === '1' ? true : false,
              })
            })
          // 更新登录坐标日志
          if (!app.globalData.localReported) {
            this.getScopeUserLocation()
              .then(() => {
                return this.getWxLocationBe();
              })
              .then((res) => {
                this.locationReport(res.latitude, res.longitude);
              })
              .catch((err) => {
                if (!err) return;
                if (/LOCATIONSWITCHOFF/.test(err.errMsg)) {
                  if (locationswitchoff) return;
                  locationswitchoff = true;
                  wx.showModal({
                    content: "设备未开启定位功能！",
                    confirmText: "知道了",
                    showCancel: false,
                  });
                }
                // console.error(err);
              });
          }
          if (this.data.tabConentIndex !== 0) return;
          this.setData({
            resblock_name: app.globalData.homeHouseSearchValue,
          });
          this.getHouseList();
        });
      }
      this.setData({
        showDialog: false,
      });
      this.data.onShowRefresh = true;
    },

    hide: function () {
      // 页面被隐藏
    },

    resize: function (size) {
      // 页面尺寸变化
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 是否显示‘添加到我的小程序’提醒
    showAddApp() {
      if (!app.globalData.sessionUser.extProps.addappSign) {
        if (this.data.isNew == 1) {
          this.setData({
            loadMyApp: false,
          });
        } else if (this.data.isNew == 2) {
          let date = new Date();
          if (!wx.getStorageSync("addApp") && app.globalData.sessionUser.mobile && !app.globalData.addApp) {
            this.setData({
              loadMyApp: true,
            });
          } else {
            if (
              date.toLocaleDateString() != wx.getStorageSync("addApp") &&
              app.globalData.sessionUser.mobile &&
              !app.globalData.addApp
            ) {
              this.setData({
                loadMyApp: true,
              });
            } else {
              this.setData({
                loadMyApp: false,
              });
            }
          }
        }
      } else {
        this.setData({
          loadMyApp: false,
        });
      }
    },

    // 不再显示‘添加到我的小程序’提醒
    noShow() {
      api.noShow({}, (res) => {
        this.setData({
          loadMyApp: false,
        });
        app.globalData.addApp = true;
      });
    },

    // ‘添加到我的小程序’提醒关闭一天
    oneDayNoShow() {
      let date = new Date();
      wx.setStorageSync("addApp", date.toLocaleDateString());
      this.setData({
        loadMyApp: false,
      });
    },

    // 获取消息通知
    getNotice() {
      api.getNotice({}, (res) => {
        if (res.data.content && res.data.content.textcontent) {
          console.log("消息通知=============", res.data.content.textcontent.length);
          this.setData({
            informComent: res.data.content.textcontent,
            informTime: res.data.content.textcontent.length,
            informDate: res.data.content.createTimeStr,
            informId: res.data.content.id,
          });
          if (!wx.getStorageSync("inform")) {
            wx.setStorageSync("inform", [{
              id: res.data.content.id,
              show: true,
            }, ]);
            this.setData({
              inform: true,
            });
          } else {
            let inform = wx.getStorageSync("inform");
            console.log("infor=====", inform);
            let newInform = inform.find((t) => t.id == res.data.content.id);
            if (newInform) {
              this.setData({
                inform: newInform.show,
              });
            } else {
              inform.push({
                id: res.data.content.id,
                show: true,
              });
              wx.setStorageSync("inform", inform);
              this.setData({
                inform: true,
              });
            }
          }
        } else {
          this.setData({
            inform: false,
          });
        }
      });
    },

    // 关闭消息通知
    closeInform() {
      this.setData({
        inform: false,
      });
      let inform = wx.getStorageSync("inform");
      for (var i = 0; i < inform.length; i++) {
        if (inform[i].id == this.data.informId) {
          inform[i].show = false;
        }
      }
      wx.setStorageSync("inform", inform);
    },

    gotoAddHouse() {
      let fn = (method) => {
        method({
          url: "/pages/addHouse/chooseHouse/chooseHouse",
        });
      };
      app
        .mobileLogin()
        .then(() => {
          fn(wx.navigateTo);
        })
        .catch(() => {
          console.log("手机号尚未授权。。。");
          app.globalData.afterMobileAuthorCallBack = () => {
            fn(wx.reLaunch);
          };
        });
    },

    handleChangeCurrentBannerIndex(e) {
      this.data.currentBannerIndex = e.detail;
      const item = this.data.modelBanners[this.data.currentBannerIndex]
      if (item) {
        let name = item.imgName;
        this.triggerEvent("onmaidianbanner", name);
      }
    },

    guidanceBanner(name) {
      const index = this.data.modelBanners.findIndex((item) => {
        return item.imgName == name;
      });
      if (index > -1) {
        this.selectComponent("#com-home-banner").handleGo({
          currentTarget: {
            dataset: {
              index
            },
          },
        });
      }
    },

    myOnShow() {
      this.fetchBanner();

      if (app.globalData.mustLogin) {
        this.gotoAddHouse();
        app.globalData.mustLogin = false;
      }
    },

    fetchBanner() {
      api.getOperateList({
        pageType: "HOMEPAGE"
      }, (res) => {
        let modelBanners = res.data.content.rows;
        this.setData({
          modelBanners,
          bannerComponentIndex: modelBanners.length == 0 ? 0 : 1,
        });

        if (modelBanners && modelBanners.length) {
          const bannerCode = app.globalData.bannerCode;
          const item = bannerCode ? modelBanners.find((v) => v.activityCode == bannerCode) : modelBanners[0];

          if (item) {
            bannerCode && this.guidanceBanner(item.imgName);
            this.triggerEvent("onmaidianbanner", item.imgName);
          }

          app.globalData.bannerCode = null;
        }
      });
    },

    handleSelectMarketIndex(e) {
      const index = e.currentTarget.dataset.index;

      this.setData({
        selectMarketIndex: index,
      });
    },

    // 坐标上报
    locationReport(lat, lng) {
      app.globalData.loginPromise.then(({
        sessionUser
      }) => {
        if (app.globalData.localReported) return;
        let extProps = sessionUser.extProps;
        app.globalData.localReported = true;

        // 首次保存坐标
        if (!extProps.lat || !extProps.lng) {
          // 更新坐标至用户信息
          api.settingEdit({
            lat,
            lng
          });
          api.pushUserFirstLogin({
            lat,
            lng
          });
          // console.log("坐标上报", "首次保存坐标");
        } else {
          // 登录log(新接口)
          // console.log("坐标上报", "登录log(新接口)");
          api.pushUserFirstLogin({
            lat,
            lng
          });
        }
      });
    },

    getLocation() {
      var that = this;
      var types = "SALES";

      this.getWxLocationBe()
        .then((res) => {
          let latitude = res.latitude;
          let longitude = res.longitude;
          wx.setStorageSync("latitude", latitude); //当前位置的经纬度
          wx.setStorageSync("longitude", longitude);

          this.locationReport(latitude, longitude);

          that.getCurrentCityByLatlng(latitude, longitude).then((currentCity) => {
            wx.setStorageSync("currentCity", currentCity);
            that.setData({
              currentCity: currentCity,
              // houseTypes: 'NEWHOUSE'
            });

            if (types == "RENT") {
              that.setData({
                contentHeaderTitle: ["区域", "租金", "房型", "更多"],
                sort: [
                  //排序
                  {
                    text: "租金由低到高",
                    types: "del.total_prices",
                    order: "asc nulls last"
                  },
                  {
                    text: "租金由高到低",
                    types: "del.total_prices",
                    order: "desc nulls last"
                  },
                  {
                    text: "面积由小到大",
                    types: "hou.build_size",
                    order: "asc nulls last"
                  },
                  {
                    text: "面积由大到小",
                    types: "hou.build_size",
                    order: "desc nulls last"
                  },
                ],
              });
            } else {
              that.setData({
                contentHeaderTitle: ["区域", "价格", "房型", "更多"],
                sort: [
                  //排序
                  {
                    text: "总价由低到高",
                    types: "del.total_prices",
                    order: "asc nulls last"
                  },
                  {
                    text: "总价由高到低",
                    types: "del.total_prices",
                    order: "desc nulls last"
                  },
                  {
                    text: "单价从低到高",
                    types: "del.unit_price",
                    order: "asc nulls last"
                  },
                  {
                    text: "单价从高到低",
                    types: "del.unit_price",
                    order: "desc nulls last"
                  },
                  {
                    text: "面积由小到大",
                    types: "hou.build_size",
                    order: "asc nulls last"
                  },
                  {
                    text: "面积由大到小",
                    types: "hou.build_size",
                    order: "desc nulls last"
                  },
                ],
              });
            }
            listData = {
              delegationType: types, //租售类型: 租：RENT 售：SALES 全部：这个参数不要传
              pageSize: 100, //单页数据条数
              page: 1, //当前页数
              buildSize: [], //面积
              area: [], //区域编号
              price: [], //价格
              floor: [], //层高
              room: [], //室数
              direction: [], //朝向
              decorate: [], //装修
              buildType: [], //类型
              distance: null, //距离
              tag: [], //标签
              order: null, //升序：asc nulls last,降序：desc
              sort: null, //最近更新：del.update_time, 最近跟进：fol.update_time  最近带看: show.update_time 总价:del.total_prices 单价:del.unit_price 面积:hou.build_size
              lat: null, //坐标
              lng: null,
              resblock_id: "",
            };
            area = []; //区域 一级选择（区）
            distance = null; //距离
            price = []; //price价格
            room = []; //室数
            order = ""; //升序降序
            buildSize = []; //面积
            floor = []; //楼层
            direction = []; //朝向
            decorate = []; //装修
            buildType = []; //类型
            tag = []; //标签

            if (++this.data.getLocationCount > 1) {
              that.getHouseList();
            }
          });
        })
        .catch(() => {
          //判断是否获得了用户地理位置授权
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting["scope.userLocation"]) {
                that.openConfirm();
              }
            },
          });
        });
    },

    openConfirm() {
      var that = this,
        currentCity = {};
      wx.showModal({
        content: "检测到您没打开定位权限，是否去设置打开？",
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          //点击“确认”时打开设置页面
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                that.getLocation();
              },
            });
          } else {
            currentCity.city = "上海市";
            currentCity.cityCode = "310000";
            wx.setStorageSync("currentCity", currentCity);
            that.setData({
              currentCity: currentCity,
            });
          }
        },
      });
    },

    updateCurrentStatus() {
      const index = TAB_LIST_NAMES.indexOf(this.data.houseTypes);
      wx.setStorageSync("currentStatus", index + 1);
    },
    changeLists(e) {
      var that = this;
      var current = parseInt(e.currentTarget.dataset.current),
        types = e.currentTarget.dataset.type;

      if (current == this.data.currentId) {
        return;
      }
      that.setData({
        showDialog: false,
        isFirst: false,
        houseList: [],
        isFetchingHouse: true,
        currentId: current,
        houseTypes: types,
        current: -1,
        isChangeList: 1,
      });

      listData.delegationType = types;
      wx.setStorageSync("currentStatus", current);

      that.areaReset();
      that.moreReset();
      that.roomReset();

      this.updateCurrentStatus();
      if (types == "RENT") {
        that.setData({
          contentHeaderTitle: ["区域", "租金", "房型", "更多"],
          sort: [
            //排序
            {
              text: "租金由低到高",
              types: "del.total_prices",
              order: "asc nulls last"
            },
            {
              text: "租金由高到低",
              types: "del.total_prices",
              order: "desc nulls last"
            },
            {
              text: "面积由小到大",
              types: "hou.build_size",
              order: "asc nulls last"
            },
            {
              text: "面积由大到小",
              types: "hou.build_size",
              order: "desc nulls last"
            },
          ],
        });
        const newpriceReset = this.data.priceRentArr;
        var contentHeaderTitle = this.data.contentHeaderTitle;
        contentHeaderTitle.splice(1, 1, "租金");
        newpriceReset.forEach(function (item, index) {
          item.select = false;
        });
        price = [];
        listData.price = price;
        this.setData({
          contentHeaderTitle: contentHeaderTitle,
          priceRentArr: newpriceReset,
          isPriceChange: true,
          minPriceValue: "",
          maxPriceValue: "",
          isHouse: 1,
        });
      } else {
        that.setData({
          contentHeaderTitle: ["区域", "价格", "房型", "更多"],
          sort: [
            //排序
            {
              text: "总价由低到高",
              types: "del.total_prices",
              order: "asc nulls last"
            },
            {
              text: "总价由高到低",
              types: "del.total_prices",
              order: "desc nulls last"
            },
            {
              text: "单价从低到高",
              types: "del.unit_price",
              order: "asc nulls last"
            },
            {
              text: "单价从高到低",
              types: "del.unit_price",
              order: "desc nulls last"
            },
            {
              text: "面积由小到大",
              types: "hou.build_size",
              order: "asc nulls last"
            },
            {
              text: "面积由大到小",
              types: "hou.build_size",
              order: "desc nulls last"
            },
          ],
        });
        const newPriceArr = this.data.priceArr;
        var contentHeaderTitle = this.data.contentHeaderTitle;
        contentHeaderTitle.splice(1, 1, "价格");
        newPriceArr.forEach(function (item, index) {
          item.select = false;
        });
        price = [];
        listData.price = price;
        this.setData({
          contentHeaderTitle: contentHeaderTitle,
          priceArr: newPriceArr,
          isPriceChange: true,
          minPriceValue: "",
          maxPriceValue: "",
          isHouse: 1,
        });
      }
      listData = {
        delegationType: types, //租售类型: 租：RENT 售：SALES 全部：这个参数不要传
        pageSize: 100, //页数
        page: 1, //当前页数
        buildSize: [], //面积
        area: [], //区域编号
        price: [], //价格
        floor: [], //层高
        room: [], //室数
        direction: [], //朝向
        decorate: [], //装修
        buildType: [], //类型
        distance: null, //距离
        tag: [], //标签
        order: null, //升序：asc nulls last,降序：desc
        sort: null, //最近更新：del.update_time, 最近跟进：fol.update_time  最近带看: show.update_time 总价:del.total_prices 单价:del.unit_price 面积:hou.build_size
        lat: null, //坐标
        lng: null,
        resblock_id: "",
      };
      area = []; //区域 一级选择（区）
      distance = null; //距离
      price = []; //price价格
      room = []; //室数
      order = ""; //升序降序
      buildSize = []; //面积
      floor = []; //楼层
      direction = []; //朝向
      decorate = []; //装修
      buildType = []; //类型
      tag = []; //标签
      that.getHouseList();
    },

    changeList(e) {
      const index = wx.getStorageSync("currentStatus") || 1;
      var that = this;
      var types = TAB_LIST_NAMES[index - 1];

      this.setData({
        currentId: index,
        houseTypes: types,
        current: -1,
        isChangeList: 1,
      });

      listData.delegationType = types;

      this.updateCurrentStatus();
      if (types == "RENT") {
        that.setData({
          contentHeaderTitle: ["区域", "租金", "房型", "更多"],
          sort: [
            //排序
            {
              text: "租金由低到高",
              types: "del.total_prices",
              order: "asc nulls last"
            },
            {
              text: "租金由高到低",
              types: "del.total_prices",
              order: "desc nulls last"
            },
            {
              text: "面积由小到大",
              types: "hou.build_size",
              order: "asc nulls last"
            },
            {
              text: "面积由大到小",
              types: "hou.build_size",
              order: "desc nulls last"
            },
          ],
        });
      } else {
        that.setData({
          contentHeaderTitle: ["区域", "价格", "房型", "更多"],
          sort: [
            //排序
            {
              text: "总价由低到高",
              types: "del.total_prices",
              order: "asc nulls last"
            },
            {
              text: "总价由高到低",
              types: "del.total_prices",
              order: "desc nulls last"
            },
            {
              text: "单价从低到高",
              types: "del.unit_price",
              order: "asc nulls last"
            },
            {
              text: "单价从高到低",
              types: "del.unit_price",
              order: "desc nulls last"
            },
            {
              text: "面积由小到大",
              types: "hou.build_size",
              order: "asc nulls last"
            },
            {
              text: "面积由大到小",
              types: "hou.build_size",
              order: "desc nulls last"
            },
          ],
        });
      }
      listData = {
        delegationType: types, //租售类型: 租：RENT 售：SALES 全部：这个参数不要传
        pageSize: 100, //页数
        page: 1, //当前页数
        buildSize: [], //面积
        area: [], //区域编号
        price: [], //价格
        floor: [], //层高
        room: [], //室数
        direction: [], //朝向
        decorate: [], //装修
        buildType: [], //类型
        distance: null, //距离
        tag: [], //标签
        order: null, //升序：asc nulls last,降序：desc
        sort: null, //最近更新：del.update_time, 最近跟进：fol.update_time  最近带看: show.update_time 总价:del.total_prices 单价:del.unit_price 面积:hou.build_size
        lat: null, //坐标
        lng: null,
        resblock_id: "",
      };
      area = []; //区域 一级选择（区）
      distance = null; //距离
      price = []; //price价格
      room = []; //室数
      order = ""; //升序降序
      buildSize = []; //面积
      floor = []; //楼层
      direction = []; //朝向
      decorate = []; //装修
      buildType = []; //类型
      tag = []; //标签
      that.getHouseList();
    },

    // 侧边栏的选择
    handleNavClick(e) {
      const index = e.currentTarget.dataset.navIndex;
      this.setData({
        currentSelectNavIndex: index,
        mainContentScrollId: `scrollItem-${index}`,
      });
    },

    tabChange(e) {
      const that = this,
        current = parseInt(e.detail.current);

      that.setData({
        current: current,
      });
    },

    //关闭无房源弹窗
    hideNoHouDialog() {
      this.setData({
        isFirst: false,
      });
    },

    //筛选--区域 重置
    areaReset() {
      var contentHeaderTitle = this.data.contentHeaderTitle;
      contentHeaderTitle.splice(0, 1, "区域");

      area = []; //区域 一级选择（区）
      distance = null; //距离
      listData.area = area;
      listData.distance = distance;
      listData.page = 1;
      this.setData({
        contentHeaderTitle: contentHeaderTitle,
        areaIndex: 0, //区域中 区 选择当前选中index
        bizBlockIndex: 0, //区域中商圈当前选中index
        distanceIndex: 0, //区域 附近当前选中index
      });
    },

    //筛选--选择商圈
    chooseBizBlock(e) {
      const bizBlockIndex = e.currentTarget.dataset.bizblockindex;
      this.setData({
        bizBlockIndex: bizBlockIndex,
      });
    },

    //筛选--选择区域--展示商圈
    chooseArea(e) {
      var areaIndex = parseInt(e.currentTarget.dataset.areaindex),
        areaId = e.currentTarget.dataset.areaid ? e.currentTarget.dataset.areaid : null,
        areaName = e.currentTarget.dataset.areaname ? e.currentTarget.dataset.areaname : null,
        newArr = [];
      this.setData({
        areaIndex: areaIndex,
      });
      newArr.push(areaName);
      area = newArr;
      listData.area = areaIndex == 0 ? null : area;
    },
    //筛选--区域--附近
    changeDistance(e) {
      var distanceIndex = parseInt(e.currentTarget.dataset.distanceindex);
      console.log("latitude", wx.getStorageSync("latitude"));
      console.log("longitude", wx.getStorageSync("longitude"));
      this.setData({
        distanceIndex: distanceIndex,
      });
      distance = distanceIndex;
      listData.distance = distance == 0 ? null : distance;
    },

    //筛选--标签
    changeTag(e) {
      const that = this,
        newTagArr = that.data.tagArr,
        index = e.currentTarget.dataset.index,
        value = e.currentTarget.dataset.value;
      newTagArr[index].select = !newTagArr[index].select;

      if (newTagArr[index].select) {
        tag.push(value);
      } else {
        tag.forEach(function (item, i) {
          if (value == item) {
            tag.splice(i, 1);
          }
        });
      }
      listData.tag = tag;
      that.setData({
        tagArr: newTagArr,
      });
    },

    //筛选--类型
    changeBbuildType(e) {
      const that = this,
        newBuildTypeArr = that.data.buildTypeArr,
        index = e.currentTarget.dataset.index,
        value = e.currentTarget.dataset.value;
      newBuildTypeArr[index].select = !newBuildTypeArr[index].select;
      if (newBuildTypeArr[index].select) {
        buildType.push(value);
      } else {
        buildType.forEach(function (item, i) {
          if (value == item) {
            buildType.splice(i, 1);
          }
        });
      }
      listData.buildType = buildType;
      that.setData({
        buildTypeArr: newBuildTypeArr,
      });
    },

    //筛选--装修
    changeDecorate(e) {
      const that = this,
        newDecorateArr = that.data.decorateArr,
        index = e.currentTarget.dataset.index,
        value = e.currentTarget.dataset.value;
      newDecorateArr[index].select = !newDecorateArr[index].select;
      console.log(newDecorateArr[index].select);
      if (newDecorateArr[index].select) {
        decorate.push(value);
      } else {
        decorate.forEach(function (item, i) {
          if (value == item) {
            decorate.splice(i, 1);
          }
        });
      }
      listData.decorate = decorate;
      that.setData({
        decorateArr: newDecorateArr,
      });
    },

    //筛选--朝向
    changeDirection(e) {
      const that = this,
        newDirectionArr = that.data.directionArr,
        index = e.currentTarget.dataset.index,
        value = e.currentTarget.dataset.value;
      newDirectionArr[index].select = !newDirectionArr[index].select;

      if (newDirectionArr[index].select) {
        direction.push(value);
      } else {
        direction.forEach(function (item, i) {
          if (value == item) {
            direction.splice(i, 1);
          }
        });
      }
      listData.direction = direction;
      that.setData({
        directionArr: newDirectionArr,
      });
    },

    //筛选--楼层
    changeFloor(e) {
      const that = this,
        newFloorArr = that.data.floorArr,
        index = e.currentTarget.dataset.index,
        max = e.currentTarget.dataset.max,
        min = e.currentTarget.dataset.min;
      newFloorArr[index].select = !newFloorArr[index].select;
      var obj = new Object();
      obj.min = min;
      if (max) {
        //以上
        obj.max = max;
      }

      if (newFloorArr[index].select) {
        floor.push(obj);
      } else {
        floor.forEach(function (item, i) {
          if (obj.min == item.min) {
            floor.splice(i, 1);
          }
        });
      }
      listData.floor = floor;
      that.setData({
        floorArr: newFloorArr,
      });
    },

    // 选择楼层（新）
    handleBuildChange(e) {
      const {
        name,
        index
      } = e.currentTarget.dataset;
      console.log({
        name,
        index
      });
      const select = this.data.buildNumNewList[index].select;

      this.setData({
        [`buildNumNewList[${index}].select`]: !select,
      });

      listData.buildNumNew = this.data.buildNumNewList.filter((v) => v.select).map((v) => v.name);
    },

    //筛选--面积输入 最底
    customMinBuildSize(e) {
      var minprice = parseInt(e.detail.value);
      this.setData({
        minBuildSizeValue: minprice,
      });
      listData.buildSize = buildSize;
    },

    //筛选--面积输入 最高
    customMaxBuildSize(e) {
      var maxprice = parseInt(e.detail.value);
      this.setData({
        maxBuildSizeValue: maxprice,
      });
      var obj = {
        max: "",
        min: ""
      };
      if (this.data.minBuildSizeValue != "") {
        obj.min = this.data.minBuildSizeValue;
      }

      if (!isNaN(maxprice) && maxprice > obj.min) {
        obj.max = maxprice;
        this.setData({
          maxBuildSizeValue: maxprice,
        });
        if (buildSize[0] == undefined) {
          buildSize.push(obj);
        } else {
          buildSize.splice(0, 1, obj);
        }

        listData.buildSize = buildSize;
      } else {}
    },

    // 判断手写面积逻辑
    max_min() {
      if (this.data.maxBuildSizeValue < this.data.minBuildSizeValue) {
        // console.log("取消选中状态")
        this.setData({
          maxBuildSizeValue: "", //取消选中状态
        });
        wx.showToast({
          title: "请输入正确的面积范围",
          icon: "none",
          duration: 3000,
        });
        // console.log(this.data.isDisabled)
      }
    },
    //筛选--面积输入聚焦
    customBuildSizeFocus() {
      const newBuildSize = this.data.buildSize;
      newBuildSize.forEach(function (item, index) {
        item.select = false;
      });
      price = [];
      listData.buildSize = [];
      this.setData({
        buildSize: newBuildSize,
      });
    },

    //筛选--面积
    changeBuildSize(e) {
      const that = this,
        newBuildSize = that.data.buildSize,
        index = e.currentTarget.dataset.index,
        max = e.currentTarget.dataset.max ? e.currentTarget.dataset.max : false,
        min = e.currentTarget.dataset.min ? e.currentTarget.dataset.min : false;
      newBuildSize[index].select = !newBuildSize[index].select;
      if (that.data.minBuildSizeValue != "" || that.data.maxBuildSizeValue != "") {
        buildSize = [];
        that.setData({
          minBuildSizeValue: "", //输入最面积
          maxBuildSizeValue: "", //输入最面积
        });
      }
      var obj = new Object();
      if (!max) {
        //以上
        obj.min = min;
        if (buildSize.length == 0 || newBuildSize[index].select) {
          buildSize.push(obj);
        } else {
          buildSize.forEach(function (item, i) {
            if (obj.min == item.min) {
              buildSize.splice(i, 1);
            }
          });
        }
      } else if (!min) {
        //以下
        obj.max = max;
        if (buildSize.length == 0 || newBuildSize[index].select) {
          buildSize.push(obj);
        } else {
          buildSize.forEach(function (item, i) {
            if (obj.max == item.max) {
              buildSize.splice(i, 1);
            }
          });
        }
      } else {
        obj.min = min;
        obj.max = max;
        if (buildSize.length == 0 || newBuildSize[index].select) {
          buildSize.push(obj);
        } else {
          buildSize.forEach(function (item, i) {
            if (obj.min == item.min && obj.max == item.max) {
              buildSize.splice(i, 1);
            }
          });
        }
      }
      listData.buildSize = buildSize;
      // console.log(listData.buildSize)
      that.setData({
        buildSize: newBuildSize,
      });
    },

    //筛选--排序
    changeSort(e) {
      const index = e.currentTarget.dataset.index,
        order = e.currentTarget.dataset.order ? e.currentTarget.dataset.order : false;
      this.setData({
        moreSortActive: index,
      });
      if (order) {
        listData.order = order;
      }
      listData.sort = this.data.sort[index].types;
    },

    //筛选--价格房型 室数
    changeRoom(e) {
      const that = this,
        newRoomArr = that.data.roomArr,
        index = e.currentTarget.dataset.index,
        value = e.currentTarget.dataset.value;
      newRoomArr[index].select = !newRoomArr[index].select;

      if (newRoomArr[index].select) {
        room.push(value);
      } else {
        room.forEach(function (item, i) {
          if (value == item) {
            room.splice(i, 1);
          }
        });
      }
      listData.room = room;
      that.setData({
        roomArr: newRoomArr,
      });
    },

    //筛选--价格选择
    changePrice(e) {
      const that = this,
        newPriceArr = that.data.houseTypes == "SALES" ? that.data.priceArr : that.data.priceRentArr,
        index = e.currentTarget.dataset.index,
        max = e.currentTarget.dataset.max ? e.currentTarget.dataset.max : false,
        min = e.currentTarget.dataset.min ? e.currentTarget.dataset.min : false;
      newPriceArr[index].select = !newPriceArr[index].select;

      if (that.data.minPriceValue != "" || that.data.maxPriceValue != "") {
        price = [];
        that.setData({
          minPriceValue: "", //输入最低价
          maxPriceValue: "", //输入最高价
        });
      }
      var obj = new Object();
      if (!max) {
        //以上
        obj.min = min;
        if (price.length == 0 || newPriceArr[index].select) {
          price.push(obj);
        } else {
          price.forEach(function (item, i) {
            if (obj.min == item.min) {
              price.splice(i, 1);
            }
          });
        }
      } else if (!min) {
        //以下
        obj.max = max;
        if (price.length == 0 || newPriceArr[index].select) {
          price.push(obj);
        } else {
          price.forEach(function (item, i) {
            if (obj.max == item.max) {
              price.splice(i, 1);
            }
          });
        }
      } else {
        obj.min = min;
        obj.max = max;
        if (price.length == 0 || newPriceArr[index].select) {
          price.push(obj);
        } else {
          price.forEach(function (item, i) {
            if (obj.min == item.min && obj.max == item.max) {
              price.splice(i, 1);
            }
          });
        }
      }

      listData.price = price;
      if (that.data.houseTypes == "SALES") {
        that.setData({
          priceArr: newPriceArr,
        });
      } else {
        that.setData({
          priceRentArr: newPriceArr,
        });
      }
    },

    //筛选--价格输入聚焦
    customPriceFocus() {
      const that = this,
        newPriceArr = that.data.houseTypes == "SALES" ? that.data.priceArr : that.data.priceRentArr;
      newPriceArr.forEach(function (item, index) {
        item.select = false;
      });
      price = [];
      listData.price = price;
      if (that.data.houseTypes == "SALES") {
        this.setData({
          priceArr: newPriceArr,
          contentHeaderTitle: ["区域", "价格", "房型", "更多"],
        });
      } else {
        this.setData({
          priceRentArr: newPriceArr,
          contentHeaderTitle: ["区域", "租金", "房型", "更多"],
        });
      }
    },

    //筛选--价格输入 最底价
    customMinPrice(e) {
      var that = this,
        value = parseInt(e.detail.value);
      var obj = {};
      if (this.data.maxPriceValue != "") {
        if (that.data.houseTypes == "SALES") {
          obj.max = this.data.maxPriceValue * 10000;
        } else {
          obj.max = this.data.maxPriceValue;
        }
      }
      if (!isNaN(value)) {
        if (that.data.houseTypes == "SALES") {
          obj.min = value * 10000;
        } else {
          obj.min = value;
        }
        this.setData({
          minPriceValue: value, //输入最低价
        });
      }
      price.splice(0, price.length, obj);
      listData.price = price;
    },

    //筛选--价格输入 最高价
    customMaxPrice(e) {
      var that = this,
        value = parseInt(e.detail.value);
      var obj = {};
      if (this.data.minPriceValue != "") {
        if (that.data.houseTypes == "SALES") {
          obj.min = this.data.minPriceValue * 10000;
        } else {
          obj.min = this.data.minPriceValue;
        }
      }
      if (!isNaN(value)) {
        if (that.data.houseTypes == "SALES") {
          obj.max = value * 10000;
        } else {
          obj.max = value;
        }
        this.setData({
          maxPriceValue: value,
        });
      }
      price.splice(0, price.length, obj);
      listData.price = price;
    },

    //筛选--不限制价格
    priceReset(e) {
      const newPriceArr = this.data.priceArr;
      newPriceArr.forEach(function (item, index) {
        item.select = false;
      });
      price = [];
      listData.price = price;
      this.setData({
        priceArr: newPriceArr,
        isPriceChange: true,
        minPriceValue: "",
        maxPriceValue: "",
        isHouse: 1,
      });

      const newpriceReset = this.data.priceRentArr;
      newpriceReset.forEach(function (item, index) {
        item.select = false;
      });
      price = [];
      listData.price = price;
      this.setData({
        priceRentArr: newpriceReset,
        isPriceChange: true,
        minPriceValue: "",
        maxPriceValue: "",
        isHouse: 1,
      });
    },

    //筛选--不限制房型 室数
    roomReset() {
      const newRoomArr = this.data.roomArr;
      newRoomArr.forEach(function (item, index) {
        item.select = false;
      });
      room = [];
      listData.room = room;
      this.setData({
        roomArr: newRoomArr,
        isHouse: 1,
      });
    },

    //房源列表加载更多
    houseListLoadMore() {
      if (isLoadOver) {
        console.log("无更多数据");
        return;
      }

      // console.log("houseListLoadMore, 加载更多。。。。");
      this.getHouseList(0, true);
    },

    //获取房源列表
    getHouseList(e, isLoadMore = false) {
      // console.log("【加载房源】=================");

      const that = this;

      if (isLoadMore) {
        listData.page = pageNumber + 1;
        listData.pageSize = pageSize;
      } else {
        isLoadOver = false;
        listData.page = 1;
        listData.pageSize = pageSize;
      }

      // 上下架过滤
      if (this.data.selectMarketIndex == -1) {
        this.data.selectMarketIndex = 0;
      }
      listData.state = this.data.marketValues[this.data.selectMarketIndex];
      listData.lat = wx.getStorageSync("latitude");
      listData.lng = wx.getStorageSync("longitude");
      this.setData({
        resblock_name: app.globalData.homeHouseSearchValue,
      });

      listData.resblock_name = this.data.resblock_name;
      listData.delegationType = app.getCurrentStatusName();
      // listData.flag = "1"
      var listDataString = JSON.stringify(listData);

      if (isLoadMore) {
        this.setData({
          currentId: wx.getStorageSync("currentStatus") || 1,
          isFetchingHouse: true,
        });
      } else {
        this.setData({
          currentId: wx.getStorageSync("currentStatus") || 1,
          houseList: [],
          isFetchingHouse: true,
        });
      }

      let p1 = new Promise((resolve, reject) => {
        setTimeout(resolve, 400);
      });
      Promise.all([this.apiFetch({
        houParamVO: listDataString
      }), p1]).then((res) => {
        res = res[0];
        let content = res.data.content;
        var rowsArr = content.rows || [];
        maxPageNumber = content.total;
        pageNumber = content.page;

        if (rowsArr.length < pageSize) {
          isLoadOver = true;
        }

        if (this.data.houseTypes != "NEWHOUSE") {
          rowsArr.forEach((item, index) => {
            item.title = getActiveStr(item.title, 50);
            item.total_prices =
              item.delegation_type == "SALES" ? Math.floor((item.total_prices / 10000) * 100) / 100 : item.total_prices;
            // 已下架数据
            item.isSoldOutState = that.data.selectMarketIndex == 1;
          });
        }

        var houseListArr = that.data.houseList ? that.data.houseList : [];
        var newhouseListArr = houseListArr.concat(rowsArr);

        if (that.data.isHouse == 1) {
          that.setData({
            isHouse: 0,
          });
        }

        that.setData({
          houseList: newhouseListArr,
          total: res.data.content.total,
          isFetchingHouse: false,
        });

        if (app.globalData.searchType && this.data.resblock_name && listData.page == 1) {
          wx.gio("track", constant.SEARCH_SUCCESS, {
            [constant.SEARCHFROM_VAR]: app.globalData.searchType,
            [constant.IFSEARCHRESULT_VAR]: !!rowsArr.length,
            [constant.SEARCHWORD_VAR]: this.data.resblock_name,
            [constant.SEARCHSOURCE_VAR]: constant.INDEX_PAGE_SEARCH,
          });
        }
      });
    },

    //重置
    moreReset() {
      this.resetNewHouseData();
      this.priceReset();
      this.roomReset();
      const that = this,
        newBuildSize = that.data.buildSize,
        newFloorArr = that.data.floorArr,
        newDirectionArr = that.data.directionArr,
        newDecorateArr = that.data.decorateArr,
        newBuildTypeArr = that.data.buildTypeArr,
        buildNumNewList = that.data.buildNumNewList,
        newTagArr = that.data.tagArr;

      newBuildSize.forEach(function (item) {
        item.select = false;
      });
      newFloorArr.forEach(function (item) {
        item.select = false;
      });
      newDirectionArr.forEach(function (item) {
        item.select = false;
      });
      newDecorateArr.forEach(function (item) {
        item.select = false;
      });
      newBuildTypeArr.forEach(function (item) {
        item.select = false;
      });
      newTagArr.forEach(function (item) {
        item.select = false;
      });
      buildNumNewList.forEach(function (item) {
        item.select = false;
      });

      buildSize = [];
      listData.sort = null;
      listData.order = null; //升序：asc nulls last,降序：desc
      listData.buildSize = buildSize; //面积
      listData.floor = []; //层高
      listData.buildNumNew = [];
      listData.direction = []; //朝向
      listData.decorate = []; //装修
      listData.buildType = []; //类型
      listData.tag = []; //标签
      that.setData({
        buildSize: newBuildSize,
        floorArr: newFloorArr,
        buildNumNewList: buildNumNewList,
        directionArr: newDirectionArr,
        decorateArr: newDecorateArr,
        buildTypeArr: newBuildTypeArr,
        tagArr: newTagArr,
        minPriceValue: "", //输入最低价
        maxPriceValue: "", //输入最高价
        moreSortActive: -1, //排序选中
        // showDialog: false,
        // current: 0,//取消选中状态
        minBuildSizeValue: "",
        maxBuildSizeValue: "",
        selectMarketIndex: -1,
      });
    },

    //顶部标题筛选
    titleFilter() {
      const that = this,
        contentHeaderTitle = that.data.contentHeaderTitle;
      listData.page = 1;
      if (area.length == 1 && distance == null) {
        contentHeaderTitle.splice(0, 1, area[0]);
      } else if (area.length == 0 && distance) {
        contentHeaderTitle.splice(0, 1, distance + "km");
      } else if (distance == 0) {
        contentHeaderTitle.splice(0, 1, "不限");
      }
      if (price.length == 0) {
        if (that.data.houseTypes == "SALES") {
          contentHeaderTitle.splice(1, 1, `价格`);
        } else {
          contentHeaderTitle.splice(1, 1, `租金`);
        }
      } else if (price.length == 1) {
        if (price[0].min == undefined) {
          if (that.data.houseTypes == "SALES") {
            contentHeaderTitle.splice(1, 1, `${price[0].max / 10000}万以下`);
          } else {
            contentHeaderTitle.splice(1, 1, `${price[0].max}万以下`);
          }
        } else if (price[0].max == undefined) {
          if (that.data.houseTypes == "SALES") {
            contentHeaderTitle.splice(1, 1, `${price[0].min / 10000}万以上`);
          } else {
            contentHeaderTitle.splice(1, 1, `${price[0].min}万以上`);
          }
        } else {
          if (that.data.houseTypes == "SALES") {
            contentHeaderTitle.splice(1, 1, `${price[0].min / 10000}-${price[0].max / 10000}万`);
          } else {
            contentHeaderTitle.splice(1, 1, `${price[0].min}-${price[0].max}万`);
          }
        }

        if (that.data.houseTypes != "SALES") {
          contentHeaderTitle.splice(1, 1, `租金`);
        } else {
          contentHeaderTitle.splice(1, 1, `价格`);
        }
      } else {
        if (that.data.houseTypes == "SALES") {
          contentHeaderTitle.splice(1, 1, `价格(多选)`);
        } else {
          contentHeaderTitle.splice(1, 1, `租金(多选)`);
        }
      }
      if (room.length == 0) {
        contentHeaderTitle.splice(2, 1, `房型`);
      } else if (room.length == 1) {
        if (room[0] == 6) {
          contentHeaderTitle.splice(2, 1, `5室以上`);
        } else {
          contentHeaderTitle.splice(2, 1, `${room[0]}室`);
        }
      } else {
        contentHeaderTitle.splice(2, 1, `房型(多选)`);
      }

      that.setData({
        contentHeaderTitle: contentHeaderTitle,
        showDialog: false,
      });
      that.checkedState();
      that.getHouseList(1);
      // console.log("titleFilter, 加载更多。。。。");
    },

    checkedState() {
      var that = this;
      //是否选中
      var current = that.data.current,
        state = this.data.showDialog;
      if (!state) {
        if (current == 1) {
          if (listData.area == null || (listData.area.length == 0 && distance == null)) {
            that.setData({
              current: 0, //取消选中状态
            });
          }
        } else if (current == 2) {
          if (listData.price.length == 0) {
            that.setData({
              current: 0, //取消选中状态
            });
          }
        } else if (current == 3) {
          if (listData.room.length == 0) {
            that.setData({
              current: 0, //取消选中状态
            });
          }
        } else if (current == 4) {
          if (
            listData.order == null &&
            listData.buildSize.length == 0 &&
            listData.floor.length == 0 &&
            listData.direction.length == 0 &&
            listData.decorate.length == 0 &&
            listData.buildType.length == 0 &&
            listData.tag.length == 0
          ) {
            that.setData({
              current: 0, //取消选中状态
            });
          }
        }
      }
    },

    //悬浮按钮筛选
    filterMyList(e) {
      const that = this,
        types = e.currentTarget.dataset.type,
        typesValue = e.currentTarget.dataset.delegationtype,
        index = e.currentTarget.dataset.index,
        icon = e.currentTarget.dataset.activeicon;
      listData.page = 1;
      that.toggleListTabDialog();
      for (var k in listData) {
        if (k == types) {
          listData[k] = typesValue;
        } else {
          listData[k] = null;
        }
      }
      listData.page = 1;
      listData.pageSize = 10;
      that.setData({
        filterTypeActive: index,
        filterTypeIconActive: icon,
      });
      that.setData({
        tabHouseTypeState: index,
      });
      that.getHouseList();
      // console.log("filterMyList, 加载更多。。。。");
    },

    //滚动时是否固定头部
    pageScroll(e) {
      const that = this;
      if (e.detail.scrollTop >= 45) {
        that.setData({
          fixedState: true, //是否定位
        });
      } else {
        that.setData({
          fixedState: false, //是否定位
        });
      }
    },

    //跳转搜索楼盘
    goSearch() {
      wx.navigateTo({
        url: `/pages/mixSearch/mixSearch?placeholder=${this.data.inputData}&appKey=homeHouseSearchValue&searchTextValue=${this.data.resblock_name}`,
      });
    },

    // 清除小区搜索词
    hanldeClearSearchValue() {
      app.globalData.homeHouseSearchValue = "";

      this.getHouseList();
    },

    //跳转新增房源
    goChooseHouse() {
      let that = this;
      let mobile = app.globalData.sessionUser.mobile;
      if (!mobile) {
        this.triggerEvent("isFirstStateFunc", false);
      }
      let fn = (method) => {
        method({
          url: "/pages/gatherHouse/addHouseMethod/addHouseMethod",
        });
      };
      app
        .mobileLogin()
        .then(() => {
          fn(wx.navigateTo);
        })
        .catch(() => {
          console.log("手机号尚未授权。。。");
          app.globalData.afterMobileAuthorCallBack = () => {
            fn(wx.reLaunch);
          };
        });
    },

    //区域切换
    goAreaList(e) {
      var tabAreaTitleIndex = e.currentTarget.dataset.tabareatitleindex;
      this.setData({
        tabAreaTitleIndex: tabAreaTitleIndex,
      });
      if (tabAreaTitleIndex == 0) {
        distance = null; //距离
        listData.distance = distance;
        this.setData({
          distanceIndex: 0, //区域 附近当前选中index
        });
      } else {
        area = []; //区域 一级选择（区）
        listData.area = area;
        this.setData({
          isAreaSecondShow: false,
          areaIndex: 0, //区域中 区 选择当前选中index
          bizBlockIndex: 0, //区域中商圈当前选中index
        });
      }
    },

    //下拉框
    toggleDialog(e) {
      var that = this;
      var current = e.currentTarget.dataset.current;
      if (current == 1) {
        //获取区域列表
        wx.getStorage({
          key: "currentCity",
          success(res) {
            var cityCode = res.data.cityCode;
            api.getAreaList({}, cityCode, (data) => {
              that.setData({
                areas: data.data.content,
              });
            });
          },
        });
      }
      if (!current) {
        current = this.data.current;
        this.setData({
          showDialog: false,
        });
      } else if (current == this.data.current) {
        this.setData({
          showDialog: !this.data.showDialog,
        });
      } else {
        this.setData({
          showDialog: true,
        });
      }

      if (current) {
        this.setData({
          current: current,
        });
      }
      that.checkedState();
    },

    //跳转房源列表
    goRentalHouseDetail(e) {
      const houdelid = e.currentTarget.dataset.houdelid;
      const tab = e.detail ? e.detail.tab : '';
      wx.navigateTo({
        url: `/pages/house/RentalHouseDetail/RentalHouseDetail?houdelid=${houdelid}&from=1&type=${this.data.houseTypes}&tab=${tab}`,
      });
      if (this.data.resblock_name) {
        wx.gio("track", constant.CLICKS_SEARCH_RESULT, {
          [constant.SEARCHWORD_VAR]: this.data.resblock_name,
          [constant.SEARCHFROM_VAR]: app.globalData.searchType,
          [constant.SEARCHSOURCE_VAR]: constant.INDEX_PAGE_SEARCH,
        });
      }
    },

    // 跳转新房详情页
    goNewHouseDetail(e) {
      const houdelid = e.currentTarget.dataset.houdelid;
      wx.navigateTo({
        url: `/pages/newBuildinghouse/newRentalHouseDetail/newRentalHouseDetail?houdelid=${houdelid}&isMay=true`,
      });

      if (this.data.resblock_name) {
        wx.gio("track", constant.CLICKS_SEARCH_RESULT, {
          [constant.SEARCHWORD_VAR]: this.data.resblock_name,
          [constant.SEARCHFROM_VAR]: app.globalData.searchType,
          [constant.SEARCHSOURCE_VAR]: constant.INDEX_PAGE_SEARCH,
        });
      }
    },

    //跳转房源详情
    goSalesDetail() {
      wx.navigateTo({
        url: "/pages/house/salesDetail/salesDetail",
      });
    },

    backRefash(option) {
      this.setData({
        backRefresh: true,
      });
    },

    //返回首页
    goIndex() {
      wx.reLaunch({
        url: "/pages/index/index?detail=true",
      });
    },

    //房源分享
    toggleShareTabDialog(e) {
      this.setData({
        shareShowDialog: !this.data.shareShowDialog,
        friendsShowDialog: false,
      });

      if (typeof e.detail != "string") return;

      xstShare();

      this.data.detailContent = null;
      if (this.data.houseTypes == "NEWHOUSE") {
        api.getnewHouseInfo({
            newDelId: e.detail,
            source: "new",
          },
          (res) => {
            console.log("房源详情data===", res.data.content);
            this.setData({
              detailContent: res.data.content,
            });
          }
        );
      } else {
        api.getHouseInfo({
            houDelId: e.detail,
          },
          (res) => {
            this.setData({
              detailContent: res.data.content,
            });
          }
        );
      }
    },

    _newHouseShare(goZhaofang) {
      var allId = {};
      var loginUserInfo = getApp().globalData.loginUserInfo;
      const sessionUser = loginUserInfo.data.content.sessionUser;
      allId.agentId = sessionUser.id;
      allId.storeId = sessionUser.extProps.storeId;
      allId.mkId = "EMP";
      allId.houDelId = this.data.detailContent.id;
      allId.newHouse = "new";
      allId.realName = sessionUser.realName;
      allId.mobile = sessionUser.mobile;
      allId.wxHeadImg = sessionUser.avatar || sessionUser.extProps.wxHeadImg;

      var extraData = {
        roomDetail: this.data.detailContent,
        allId: allId,
        type: "coupon",
      };
      extraData.roomDetail.isNewHouse = true;
      extraData.allId.isTranspond = true;

      if (goZhaofang) {
        app.globalData.houseShareBannerInfo = JSON.parse(JSON.stringify(extraData));
        console.log("app.globalData.houseShareBannerInfo==", app.globalData.houseShareBannerInfo);

        wx.gio("track", constant.SHARE_SUCCESS, {
          [constant.ROOMTYPE_VAR]: _map[this.data.houseTypes],
          [constant.SHARETYPE_VAR]: constant.HB_SHARE,
        });

        wx.navigateTo({
          url: "/pages/house/RentalHouseDetail/oldHouseShare/oldHouseShare"
        });
      } else {
        wx.navigateToMiniProgram({
          appId: "wx5adc5dd9870f6a26", //树懒找房极速版appid
          // path: 'pages/houseShare/newHouseShare/newHouseShare',
          path: "pages/houseShare/newRentalHouseDetail/newRentalHouseDetail?jingjiId=" + JSON.stringify(extraData),
          extraData: extraData,
          envVersion: util.envVersion,
          success: (res) => {
            // 打开成功
            wx.gio("track", constant.SHARE_SUCCESS, {
              [constant.ROOMTYPE_VAR]: _map[this.data.houseTypes],
              [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
            });
          },
          fail(res) {
            //
          },
        });
      }
    },

    //跳转直接分享----到树懒找房小程序---带各种ID 和房源详情的相关数据
    goShareImage(e) {
      console.log(this.data, "直接分享---");
      if (!this.data.detailContent) return;

      api.shareHouseLog({
        sourceApp: "0",
        shareType: "1",
        delId: this.data.detailContent.id || this.data.detailContent.houDelVO.id,
      });

      wx.gio("track", constant.HANDLE_SHARE, {
        [constant.ROOMTYPE_VAR]: _map[this.data.houseTypes],
        [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
        [constant.SHARESOURCE_VAR]: constant.LIST_SHARE,
      });

      if (this.data.houseTypes == "NEWHOUSE") {
        this._newHouseShare();
        return;
      }
      var allId = {};
      var loginUserInfo = getApp().globalData.loginUserInfo;
      // console.log(e.currentTarget.dataset.houdelid)
      // console.log(e)
      if (loginUserInfo) {
        allId.agentId = loginUserInfo.data.content.sessionUser.id;
        allId.storeId = loginUserInfo.data.content.sessionUser.extProps.storeId;
        allId.mkId = "EMP";
        allId.houDelId = this.data.detailContent.houDelVO.id;
      }
      var extraData = {
        allId: allId,
        type: "coupon",
      };
      extraData.allId.isTranspond = true;
      console.log("extraData", extraData);
      wx.navigateToMiniProgram({
        appId: "wx5adc5dd9870f6a26", //树懒找房极速版appid
        path: "pages/houseShare/RentalHouseDetailLite/RentalHouseDetailLite?jingjiId=" + JSON.stringify(extraData),
        extraData: extraData,
        envVersion: util.envVersion,
        success: (res) => {
          // 打开成功
          wx.gio("track", constant.SHARE_SUCCESS, {
            [constant.ROOMTYPE_VAR]: _map[this.data.houseTypes],
            [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
          });
        },
        fail(res) {
          //
        },
      });
    },

    //分享到朋友圈，复制关键信息及链接
    goSharepyq() {
      if (!this.data.detailContent) return;
      api.shareHouseLog({
        sourceApp: "0",
        shareType: "2",
        delId: this.data.detailContent.id || this.data.detailContent.houDelVO.id,
      });

      wx.gio("track", constant.HANDLE_SHARE, {
        [constant.ROOMTYPE_VAR]: _map[this.data.houseTypes],
        [constant.SHARETYPE_VAR]: constant.PYQ_SHARE,
        [constant.SHARESOURCE_VAR]: constant.LIST_SHARE,
      });

      this.setData({
        shareShowDialog: true,
        friendsShowDialog: true,
        pyqVisible: true,
      });

      if (this.data.houseTypes == "NEWHOUSE") {
        this.goSharepyqNewHouse();
        return;
      }
      let that = this;
      const houDelVO = that.data.detailContent.houDelVO;
      const priceTitle = houDelVO.delegationType == "SALES" ? '售价' : '租金';
      let price =
        houDelVO.totalPrices == -1 ?
        "暂无售价" :
        houDelVO.delegationType == "SALES" ?
        houDelVO.totalPrices / 10000 + "万" :
        houDelVO.totalPrices + "元/月";
      wx.setClipboardData({
        data: `小区：${houDelVO.resblockName}
户型：${
          houDelVO.room == -1 && houDelVO.hall
            ? "暂无户型"
            : houDelVO.room + "室" + houDelVO.hall + "厅"
        }
面积：${
          houDelVO.buildSize == -1
            ? "暂无面积"
            : houDelVO.buildSize + "m²"
        }
${priceTitle}：${price}
地址：${that.data.detailContent.houDelVO.area ? that.data.detailContent.houDelVO.area + " " : ""}${
          that.data.detailContent.houDelVO.addr
        }`,
        success: (res) => {
          wx.getClipboardData({
            success: (res) => {
              wx.showToast({
                title: "房源信息已复制到剪切板",
                icon: "none",
              });
            },
          });
        },
      });

      console.log(that.data.detailContent);
      var loginUserInfo = getApp().globalData.loginUserInfo;
      api.oldHouseInfo({
        agentid: loginUserInfo.data.content.sessionUser.id,
        openid: wx.getStorageSync("aldstat_op"),
      });
    },

    //分享到朋友圈，复制关键信息及链接
    goSharepyqNewHouse() {
      var loginUserInfo = getApp().globalData.loginUserInfo;
      api.oldHouseInfo({
        agentid: loginUserInfo.data.content.sessionUser.id,
        openid: wx.getStorageSync("aldstat_op"),
      });
    },

    // 去直播
    handleTrtc() {
      app.mobileLogin()
        .then(() => {
          wx.navigateTo({
            url: "/pages/gatherHouse/scanAddHouse/scanAddHouse"
          })
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: "/pages/gatherHouse/scanAddHouse/scanAddHouse"
            })
          }
        })
    },

    // 海报分享
    posterShareImage() {
      if (!this.data.detailContent) return;

      api.shareHouseLog({
        sourceApp: "0",
        shareType: "3",
        delId: this.data.detailContent.id || this.data.detailContent.houDelVO.id,
      });

      wx.gio("track", constant.HANDLE_SHARE, {
        [constant.ROOMTYPE_VAR]: _map[this.data.houseTypes],
        [constant.SHARETYPE_VAR]: constant.HB_SHARE,
        [constant.SHARESOURCE_VAR]: constant.LIST_SHARE,
      });

      if (this.data.houseTypes == "NEWHOUSE") {
        this._newHouseShare(true);
        return;
      }

      var allId = {};
      var loginUserInfo = getApp().globalData.loginUserInfo;
      const sessionUser = loginUserInfo.data.content.sessionUser;
      allId.agentId = sessionUser.id;
      allId.storeId = sessionUser.extProps.storeId;
      allId.mkId = "EMP";
      allId.houDelId = this.data.detailContent.houDelVO.id;
      allId.realName = sessionUser.realName;
      allId.mobile = sessionUser.mobile;
      allId.wxHeadImg = sessionUser.avatar || sessionUser.extProps.wxHeadImg;

      var extraData = {
        roomDetail: this.data.detailContent,
        allId: allId,
        type: "coupon",
      };

      extraData = JSON.parse(JSON.stringify(extraData));
      Object.assign(extraData.roomDetail, extraData.roomDetail.houDelVO);
      extraData.roomDetail.houDelVO = null;
      app.globalData.houseShareBannerInfo = extraData;
      console.log("app.globalData.houseShareBannerInfo==", app.globalData.houseShareBannerInfo);
      wx.navigateTo({
        url: "/pages/house/RentalHouseDetail/oldHouseShare/oldHouseShare"
      });
    },

    friendsShareTabDialog() {
      let that = this;
      that.setData({
        shareShowDialog: false,
        friendsShowDialog: false,
        pyqmodal: false,
        pyqVisible: false,
      });
    },

    // 获取数据
    apiFetch(data) {
      return new Promise((resolve, reject) => {
        if (this.data.houseTypes == "NEWHOUSE") {
          const item = this.data.navList.NEWHOUSE.buildingState.find((item) => {
            return item.value == "UNAVAILABLE";
          });
          const isSoldOutState = item.select;
          api.myNewHouse(this.createNewHouseFilterData(), (res) => {
            res.data.content.rows.forEach((item) => {
              if (item.program_features) {
                item.program_features = item.program_features
                  .replace(/[\{|\}]/g, "")
                  .split(",")
                  .filter((v) => !!v);
              }
              item._buildSize = [item.min_size, item.max_size]
                .filter((v) => !!v)
                .map((v) => v + "m²")
                .join("～");
              item._buildSize = item._buildSize ? "建面" + item._buildSize : "暂无面积";
              item.title = getActiveStr(item.title, 18);

              item.isSoldOutState = isSoldOutState;
            });

            resolve(res);
          });
        } else {
          api.getMyHouseList(data, (res) => {
            resolve(res);
          });
        }
      });
    },

    // 新房搜索数据 创建
    createNewHouseFilterData() {
      const obj = this.data.navList.NEWHOUSE;
      let filterValues = (arr) => {
        return arr
          .filter((item) => {
            return item.select;
          })
          .map((v) => v.value);
      };

      this.setData({
        resblock_name: app.globalData.homeHouseSearchValue,
      });
      // 在售状态
      const resblockType = filterValues(obj.sellState)[0] || "";
      // 上下架
      const houseStatus = filterValues(obj.buildingState)[0] || "AVAILABLE";
      // 单价
      const averagePrice = filterValues(obj.unitPrice);
      const order = filterValues(obj.sort)[0] || "";
      const sort = order ? "hnd.average_price" : "";
      const page = listData.page;
      const pageSize = listData.pageSize;
      // 小区名
      const resblockName = this.data.resblock_name;

      const result = {
        resblockType,
        houseStatus,
        averagePrice,
        sort,
        order,
        page,
        pageSize,
        resblockName
      };
      return result;
    },

    // 重置新房数据
    resetNewHouseData() {
      const obj = this.data.navList.NEWHOUSE;
      for (const key in obj) {
        if (key == "titles") continue;
        obj[key].forEach((item) => {
          item.select = false;
        });
      }
      this.setData({
        "navList.NEWHOUSE": obj,
      });
    },

    // 排序
    handleNewHouseSort(e) {
      const obj = this.data.navList.NEWHOUSE.sort;
      const index = e.currentTarget.dataset.index;
      const selected = obj[index].select;
      obj.forEach((item, i) => {
        item.select = i == index;
      });
      obj[index].select = !selected;
      this.setData({
        "navList.NEWHOUSE.sort": obj,
      });
    },

    // 单价
    handleNewHousePrice(e) {
      const obj = this.data.navList.NEWHOUSE;
      const index = e.currentTarget.dataset.index;
      obj.unitPrice[index].select = !obj.unitPrice[index].select;
      this.setData({
        "navList.NEWHOUSE.unitPrice": obj.unitPrice,
      });
    },

    // 销售状态
    handleNewHouseSellState(e) {
      const obj = this.data.navList.NEWHOUSE.sellState;
      const index = e.currentTarget.dataset.index;
      const selected = obj[index].select;
      obj.forEach((item, i) => {
        item.select = i == index;
      });
      obj[index].select = !selected;
      this.setData({
        "navList.NEWHOUSE.sellState": obj,
      });
    },

    // 楼盘状态
    handleNewHouseBuildingState(e) {
      const obj = this.data.navList.NEWHOUSE.buildingState;
      const index = e.currentTarget.dataset.index;
      const selected = obj[index].select;
      obj.forEach((item, i) => {
        item.select = i == index;
      });
      obj[index].select = !selected;
      this.setData({
        "navList.NEWHOUSE.buildingState": obj,
      });
    },

    onScroll(scrollTop) {
      this.selectAllComponents(".house-item").forEach((child) => child.onScroll(scrollTop))
      this.setData({
        scrollTop: scrollTop,
        scrollIng: true,
        showGetCash: false,
        hideGetCash: true,
      });
      timer = setTimeout(() => {
        if (this.data.scrollTop === scrollTop) {
          this.setData({
            scrollTop: scrollTop,
            scrollIng: false,
            showGetCash: true,
            hideGetCash: false,
          });
        } else {
          timer;
        }
      }, 1000);
    },

    fingerStart() {
      this.setData({
        finger: false,
      });
    },

    fingerEnd() {
      this.setData({
        finger: true,
      });
    },

    // 房源搬家
    goToselectwebsite() {
      app
        .mobileLogin()
        .then(() => {
          wx.navigateTo({
            url: "/pages/gatherHouse/scanAddHouse/scanAddHouse"
          });
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: "/pages/gatherHouse/scanAddHouse/scanAddHouse"
            });
          };
        });
    },

    // 免费房源
    goToviehouse() {
      this.triggerEvent("myevent", {
        tabConentIndex: 2
      });
    },

    //电脑端
    goToScanWeb() {
      app
        .checkPcLogin()
        .then((res) => {
          // 登陆过则表示 非首次登录
          let b = res ? "0" : "1";
          wx.navigateTo({
            url: `/pages/home/scanWeb/scanWeb?firstLogined=${b}`
          });
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {};
        });
    },

    //产品教程
    goToProductTutorial() {
      wx.navigateTo({
        url: "/pages/gatherHouse/productTutorial/prodctTutorial",
      });
    },

    //房雷达
    goToRadar() {
      app
        .mobileLogin(null, "房雷达")
        .then(() => {
          wx.navigateTo({
            url: "/pages/gatherHouse/radarHouse/radarHouse"
          });
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: "/pages/gatherHouse/radarHouse/radarHouse"
            });
          };
        });
    },

    goToNewInvite() {
      const url = `/pages/mine/newInvite/newFissionPage/newFissionPage?actEntre=${constant.firstEntr}`;
      app
        .mobileLogin()
        .then(() => {
          wx.navigateTo({ url, });
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({ url, });
          };
        });
    },

    goToNewSubscribe() {
      this.setData({
        unread: 0,
      });
      wx.navigateTo({
        url: "/pages/home/subscribe/list/list",
      });
    },

    goToBox() {
      wx.navigateTo({
        url: "/pages/mine/magicBox/magicBox",
      });
    },

    // 房源情报未读
    getUnreadMesgCount() {
      return new Promise((resolve, reject) => {
        api.getUnreadMesgCount({}, (res) => {
          if (res && res.data && res.data.content) {
            const {
              unreadCount
            } = res.data.content;
            this.setData({
              unread: unreadCount || 0,
            });
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    // 先拿到业主房源情报未读
    getPropertyOwner() {
      return new Promise((resolve, reject) => {
        api.getUnReadCount({}, (res) => {
          if (res && res.data && res.data.content) {
            const {
              unreadCount,
            } = res.data.content
            this.setData({
              unreadCount: unreadCount || 0,
            })
            resolve()
          } else {
            reject()
          }
        })
      })
    },

    // 到业主房源情报页面
    goToPropertyOwner() {
      // if (this.data.unreadCount !== 0) { //有未读消息时才去删除
      //   this.deleteUnReadCount()
      //   wx.navigateTo({
      //     url: "/pages/home/propertyOwner/propertyOwner"
      //   })
      // } else {
      //   wx.navigateTo({
      //     url: "/pages/home/propertyOwner/propertyOwner"
      //   })
      // }
      this.setData({
        unreadCount: 0,
      })
      wx.navigateTo({
        url: "/pages/home/propertyOwner/propertyOwner"
      })
    },

    // // 清楚业主情报未读
    // deleteUnReadCount() {
    //   return new Promise((resolve, reject) => {
    //     api.deleteUnReadCount({}, (res) => {
    //       if (res && res.data && res.data.isSuccess) {
    //         this.setData({
    //           unreadCount: 0,
    //         })
    //         resolve()
    //       } else {
    //         reject()
    //       }
    //     })
    //   })
    // },

    // 点击整个页面
    onClickHome() {
      this.selectAllComponents(".house-item").forEach((child) => child.onClick())
    },

    onRefreshList() {
      this.getHouseList();
    },

  },
});